// pages/newLottery/newLottery.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //奖品列表，最多只有三项
    array: [{
        description: '',
        name: '',
        quantity: 0,
        sort: 0
      },
      {
        description: '',
        name: '',
        quantity: 0,
        sort: 1
      },
      {
        description: '',
        name: '',
        quantity: 0,
        sort: 2
      }
    ],
    isShow:[true,false,false],//奖品列表显示判断
    name: '', //活动名称
    image: '', //活动图片
    detail: '', //抽奖说明
    conditions: ['由发起人手动开奖', '根据开奖时间开奖'],
    condiTitle: ['手动开奖', '自动开奖'],
    index: 0, //条件列表下标
    giftIdx: 1, //奖品列表可见数量
    date: '2015-09-01',
    time: '00:00',
    datetimeArray: '', //日期时间合并
    showPicker: false, //时间选择器显示控制器
    showAdd: true, //添加奖品控制器
    limitNum: 0, //开奖人数
    host: '', //地址ip

    //富文本内容
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '请输入内容',
    _focus: false,
    url: '',
  },
  //富文本内容
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },

  onEditorReady() {
    var that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context;
    }).exec();
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  /*
  *表单重置
  */
  formReset: function() {
    if (app.globalData.userInfo) {
      this.clear();
      wx.showToast({
        title: '清除成功！',
        icon: 'success',
        duration: 1000
      });
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }
  },
  /**
   * 提交表单
   */
  formSubmit: function(e) {
    var that = this
    console.log(app.globalData.openid)
    //获取奖品列表
    console.log("原本：", that.data.array)
    var giftList = that.data.array
    for (let i = 0; i < giftList.length; i++) {
      if (giftList[i].quantity == 0) {
        giftList.splice(i, 1)
        i--
      } else {
        giftList[0].sort = i
      }
    }
    console.log("删除后：", giftList)
    //将日期转换为时间戳
    var datetime = new Date(that.data.datetimeArray.replace(/-/g, "/")).getTime()
    console.log("时间戳", datetime)

    if (app.globalData.userInfo) {
      if (that.data.name == '' || giftList.length == 0 || that.data.limitNum == 0) {
        wx.showModal({
          title: '提示',
          content: '请完善活动信息'
        })
      } else {
        console.log('调用submit');
        //获取富文本
        this.editorCtx.getContents({
          success: function(res) {
            var r ={
              name: that.data.name,
              image: that.data.image,
              detail: res.html, //富文本内容
              end_time: that.data.datetimeArray,
              min_num: that.data.limitNum,
              form: that.data.condiTitle[that.data.index],
              prize: giftList
            }
            console.log(r)
            //提交表单
            wx.request({
              url: that.data.host + '/jeesite/lottery/addActivity',
              method: "POST",
              header: {
                "Content-Type": "application/json"
              },
              data: {
                "message": "addActivity",
                "openid": app.globalData.openid,
                "data": {
                  name: that.data.name,
                  image: that.data.image,
                  detail: res.html, //富文本内容
                  end_time: datetime,
                  min_num: that.data.limitNum,
                  form: that.data.condiTitle[that.data.index],
                  prize: giftList
                }
              },
              success: function(res) {
                console.log("成功",res)
              },
              fail: function(res) {
                console.log("添加失败,", res)
              }
            })
          },
          fail: function(res) {
            console.log("失败",res);
          }
        });
        console.log("调用结束");
        wx.showToast({
          title: '添加成功！',
          icon: 'success',
          duration: 1500
        });
      }
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }
  },


  /**
   * 添加奖品函数
   * 显示多个input
   */
  newGift: function(e) {
    var that = this
    var test = that.data.isShow
    var id = that.data.giftIdx
    test[id] = true
    id++
    this.setData({
      isShow: test,
      giftIdx: id
    })
    console.log(that.data.isShow)
    if (that.data.giftIdx > 2) {
      that.setData({
        showAdd: false
      })
    }
  },
  /**
   * 修改抽奖条件函数，显示日期时间选择器
   */
  bindPickerChange: function(e) {
    console.log('条件为：', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    if (e.detail.value == 1) {
      this.setData({
        showPicker: true
      })
    } else {
      this.setData({
        showPicker: false
      })
    }
  },
  bindDateChange: function(e) {
    var that = this
    console.log('日期：', e.detail.value)
    var date = e.detail.value
    var array = date + " " + that.data.time+":00"
    console.log(array)
    // var test = new Date(array.replace(/-/g, "/")).getTime()
    // console.log("时间戳",test)
    that.setData({
      date: date,
      datetimeArray: array
    })
  },
  bindTimeChange: function(e) {
    var that = this
    console.log('时间：', e.detail.value)
    var time = e.detail.value
    var array = that.data.date + " " + time + ":00"
    that.setData({
      time: time,
      datetimeArray: array
    })
  },
  /**
   * 单张图片预览
   */
  handleImagePreview(e) {
    var that = this
    var current = that.data.image
    if (app.globalData.userInfo) {
      wx.previewImage({
        current: current,
        urls: [current]
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.setData({
      host: app.globalData.ip
    })
  },
  /**
   * 上传图片
   */
  chooseImage(e) {
    var that = this
    var image = that.data.image
    if (app.globalData.userInfo) {
      if (image != "") {
        wx.navigateTo({
          url: '../logs/logs?image=' + image,
        })
      } else {
        wx.navigateTo({
          url: '../logs/logs',
        })
      }
    } else {
      wx.showModal({
        title: '未授权！',
        content: '请先提供授权信息~',
        showCancel: false,
      })
    }
  },
  /**
   * input输入框绑定数据
   */
  setName: function(e) {
    var that = this
    that.setData({
      name: e.detail.value
    })
    console.log(that.data.name)
  },
  setGrade: function(e) {
    var that = this
    var idx = e.currentTarget.dataset.index
    console.log(idx)
    var obj = that.data.array
    obj[idx].description = e.detail.value
    that.setData({
      array: obj
    })
    console.log(that.data.array)
  },
  setGiftName: function(e) {
    var that = this
    var idx = e.currentTarget.dataset.index
    console.log(idx)
    var obj = that.data.array
    obj[idx].name = e.detail.value
    that.setData({
      array: obj
    })
    console.log(that.data.array)
  },
  setGiftNum: function(e) {
    var that = this
    var idx = e.currentTarget.dataset.index
    console.log(idx)
    var obj = that.data.array
    obj[idx].quantity = e.detail.value
    that.setData({
      array: obj
    })
    console.log(that.data.array)
  },
  setLimitNum: function(e) {
    var that = this
    that.setData({
      limitNum: e.detail.value
    })
    console.log(that.data.limitNum)
  }

})